#include	<malloc.h>
#include	<fcntl.h>
#include	<io.h>
#include	<direct.h>
#include	<sys/stat.h>

#include "BaseFileSource.h"
#include "FileData.h"
#include "FString.h"


BaseFileSource::BaseFileSource (const FString &thePath) : IFileSource ("BaseFileSource")
{
//	(*sysLog) << "Created resource source " << thePath << logEndl;
	path = thePath;
}


FileData* BaseFileSource::getFile (const FString &name)
{
	FString	fileName = FString::buildFileName (path, name);

	int		file = open(fileName, O_RDONLY | O_BINARY);
	void  * ptr  = NULL;
	int		size = 0;

	if (file == -1)
		return NULL;

	size = filelength (file);
	ptr  = malloc     (size);

	if (ptr == NULL)
	{
		close (file);
		size = 0;
		return NULL;
	}

	if (read (file, ptr, size) != size)
	{
		free (ptr);
		size = 0;
		ptr  = NULL;
	}

	close (file);

	return new FileData (name, ptr, size);
}

bool IFileSource::MakeDir (const FString& path, bool tree=0)
{
	if (tree) return MakeDir (path, tree);
	return _mkdir (path) != -1;
}

